package org.jeecg.modules.lab.utensil.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.cronJob.MyEnum;
import org.jeecg.common.cronJob.entity.LabCronJob;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.lab.cert.client.UserClient;
import org.jeecg.modules.lab.cronJob.service.ILabCronJobService;
import org.jeecg.modules.lab.user.entity.SysUser;
import org.jeecg.modules.lab.utensil.entity.LabUtensilChecklist;
import org.jeecg.modules.lab.utensil.service.ILabUtensilChecklistService;
import org.jeecg.modules.lab.utensil.vo.LabUtensilChecklistVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 器具检测详情清单
 * @Author: jeecg-boot
 * @Date: 2023-08-22
 * @Version: V1.0
 */
@Api(tags = "器具检测详情清单")
@RestController
@RequestMapping("/utensil/labUtensilChecklist")
@Slf4j
public class LabUtensilChecklistController extends JeecgController<LabUtensilChecklist, ILabUtensilChecklistService> {
    @Autowired
    private ILabUtensilChecklistService labUtensilChecklistService;
    @Autowired
    private UserClient userClient;

    @Autowired
    private ILabCronJobService labCronJobService;

    /**
     * 分页列表查询
     *
     * @param labUtensilChecklist
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "器具检测详情清单-分页列表查询")
    @ApiOperation(value = "器具检测详情清单-分页列表查询", notes = "器具检测详情清单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<LabUtensilChecklist>> queryPageList(LabUtensilChecklist labUtensilChecklist,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            HttpServletRequest req) {
        QueryWrapper<LabUtensilChecklist> queryWrapper = QueryGenerator.initQueryWrapper(labUtensilChecklist, req.getParameterMap());
        Page<LabUtensilChecklist> page = new Page<LabUtensilChecklist>(pageNo, pageSize);
        queryWrapper.eq("list_state", "检定中");
        IPage<LabUtensilChecklist> pageList = labUtensilChecklistService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param labUtensilChecklist
     * @return
     */
    @AutoLog(value = "器具检测详情清单-添加")
    @ApiOperation(value = "器具检测详情清单-添加", notes = "器具检测详情清单-添加")
//   @RequiresPermissions("utensilCheckList:lab_utensil_checklist:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody LabUtensilChecklist labUtensilChecklist) {
        labUtensilChecklistService.save(labUtensilChecklist);

        if (MyEnum.sync) {
            long time = new Date().getTime();
            LabCronJob job= new LabCronJob("lab_utensil_checklist", "0", time, 1);
            labCronJobService.save(job);
        }
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param labUtensilChecklist
     * @return
     */
    @AutoLog(value = "器具检测详情清单-编辑")
    @ApiOperation(value = "器具检测详情清单-编辑", notes = "器具检测详情清单-编辑")
//   @RequiresPermissions("utensilCheckList:lab_utensil_checklist:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody LabUtensilChecklist labUtensilChecklist) {
        try {
            //同时要修改基础表中的内容
            labUtensilChecklistService.updateAll(labUtensilChecklist);

            if (MyEnum.sync) {
                long time = new Date().getTime();
                List<LabCronJob> jobs = new ArrayList<>();
                jobs.add( new LabCronJob("lab_utensil_checklist", "1", time, 1));
                jobs.add( new LabCronJob("lab_utensil", "1", time, 2));
                jobs.add( new LabCronJob("lab_device", "1", time, 3));
                labCronJobService.saveBatch(jobs);
            }
            return Result.OK("编辑成功!");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    //校验结果中批量设置时间和上传证书
    @PostMapping(value = "/setList")
    public Result<String> setList(@RequestBody List<LabUtensilChecklist> list) {
        try {

            labUtensilChecklistService.updateList(list);

            if (MyEnum.sync) {
                long time = new Date().getTime();
                List<LabCronJob> jobs = new ArrayList<>();
                jobs.add( new LabCronJob("lab_utensil_checklist", "1", time, 1));
                jobs.add( new LabCronJob("lab_utensil", "1", time, 2));
                labCronJobService.saveBatch(jobs);
            }
            return Result.ok("批量设置成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    //提交确认
    @PostMapping(value = "/submit")
    public Result<String> submit(@RequestBody LabUtensilChecklist labUtensilChecklist) {
        try {
            labUtensilChecklistService.submit(labUtensilChecklist);

            if (MyEnum.sync) {
                long time = new Date().getTime();
                List<LabCronJob> jobs = new ArrayList<>();
                jobs.add( new LabCronJob("lab_utensil_checklist", "1", time, 1));
                jobs.add( new LabCronJob("lab_utensil", "1", time, 2));

                labCronJobService.saveBatch(jobs);
            }
            return Result.ok("提交成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }

    }

    @GetMapping(value = "/queryMonth")
    public Result<Map<String, List>> queryByMonth(@RequestParam(name = "selYear", defaultValue = "") String selYear) {
        Map<String, List> map = labUtensilChecklistService.queryMonth(selYear);
        return Result.ok(map);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "器具检测详情清单-通过id删除")
    @ApiOperation(value = "器具检测详情清单-通过id删除", notes = "器具检测详情清单-通过id删除")
//   @RequiresPermissions("utensilCheckList:lab_utensil_checklist:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        labUtensilChecklistService.removeById(id);

        if (MyEnum.sync) {
            long time = new Date().getTime();
            String condition = "id='" + id + "'";
            LabCronJob job = new LabCronJob("lab_operation", "2", condition, time, 1);
            labCronJobService.save(job);
        }
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "器具检测详情清单-批量删除")
    @ApiOperation(value = "器具检测详情清单-批量删除", notes = "器具检测详情清单-批量删除")
//   @RequiresPermissions("utensilCheckList:lab_utensil_checklist:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.labUtensilChecklistService.removeByIds(Arrays.asList(ids.split(",")));

        if (MyEnum.sync) {
            long time = new Date().getTime();
            String[] idList = ids.split(",");
            labCronJobService.saveCronBatch("lab_operation","2",time,idList);
        }
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "器具检测详情清单-通过id查询")
    @ApiOperation(value = "器具检测详情清单-通过id查询", notes = "器具检测详情清单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<LabUtensilChecklist> queryById(@RequestParam(name = "id", required = true) String id) {
        LabUtensilChecklist labUtensilChecklist = labUtensilChecklistService.getById(id);
        if (labUtensilChecklist == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(labUtensilChecklist);
    }

    /**
     * 通过出厂编号查询
     * //     * @param uteRef
     *
     * @return
     */
    @GetMapping(value = "/checklist")
    public Result<List<LabUtensilChecklistVo>> queryBy(@RequestParam(name = "manuNumber", defaultValue = "") String uteRef) {
        List<LabUtensilChecklist> list = labUtensilChecklistService.list(new LambdaQueryWrapper<LabUtensilChecklist>().eq(LabUtensilChecklist::getUteRef, uteRef));
        List<LabUtensilChecklistVo> checklistVos = new ArrayList<>();
        list.forEach(e -> {
            LabUtensilChecklistVo checklistVo = new LabUtensilChecklistVo();
            BeanUtils.copyProperties(e,checklistVo);
            String[] split = checklistVo.getDri().split(",");
            String perName = "";
            for (int i = 0; i < split.length; i++) {
                SysUser user = userClient.queryById(split[i]).getResult();
                if (i == split.length - 1) {
                    perName += user.getRealname();
                    break;
                }
                perName += user.getRealname() + ",";
            }
            checklistVo.setDriName(perName);
            checklistVos.add(checklistVo);
        });
        return Result.ok(checklistVos);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param labUtensilChecklist
     */
//   @RequiresPermissions("utensilCheckList:lab_utensil_checklist:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LabUtensilChecklist labUtensilChecklist) {
        return super.exportXls(request, labUtensilChecklist, LabUtensilChecklist.class, "器具检测详情清单");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
//   @RequiresPermissions("utensilCheckList:lab_utensil_checklist:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LabUtensilChecklist.class);
    }

}
